package com.bwie.interrogation.util;


import com.bwie.interrogation.domain.AddressData;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

public class AddressRecognitionUtil {
//    public static PatientAddress AddressRecognition(String address){
    public static AddressData AddressRecognition(String address){
        String host = "https://kzaddress1.market.alicloudapi.com";
        String path = "/api/address/parse";
        String method = "POST";
        String appcode = "cd39cea0d16a44b58f8fd69f4072b01f";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("address", address);

        try {
            // 发送 HTTP 请求
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);

            // 获取响应内容
            String string = EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.println("Response: " + string); // 打印响应内容

            // 解析 JSON
            ObjectMapper objectMapper = new ObjectMapper();
            AddressData data = objectMapper.readValue(string, AddressData.class);

            // 直接返回解析后的 data 对象
            return data;

        } catch (Exception e) {
            e.printStackTrace();
            // 如果发生异常，返回一个包含错误信息的 AddressData 对象
            AddressData errorData = new AddressData();
            errorData.setCode("500");
            errorData.setMsg("Internal Server Error: " + e.getMessage());
            errorData.setSuccess(false);
            return errorData;
        }
    }
}